package com.leyou.item.web;

import com.leyou.dto.SpecGroupDTO;
import com.leyou.dto.SpecParamDTO;
import com.leyou.entity.SpecGroup;
import com.leyou.entity.SpecParam;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/spec")
public class SpecController {
    @Autowired
    private SpecGroupService specGroupService;
    @Autowired
    private SpecParamService specParamService;
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> queryGroupBycategoryId(@RequestParam("id")Long id){
        return ResponseEntity.ok(SpecGroupDTO.convertEntityList(specGroupService.query().eq("category_id",id).list()));
    }
    @GetMapping("/params")
    public ResponseEntity<List<SpecParamDTO>> queryParamsBySpecParams(
            @RequestParam(value = "categoryId",required = false)Long id,
            @RequestParam(value = "groupId",required = false)Long gid,
            @RequestParam(value = "searching",required = false)Boolean sear
    ){
        return ResponseEntity.ok(SpecParamDTO.convertEntityList(specParamService.querybyparam(id,gid,sear)));
    }
    @PostMapping("/group")
    public ResponseEntity<Void> inputGroup(@RequestBody SpecGroupDTO specGroupDTO){
        //新增用save方法
        //需要Entity对象
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        specGroupService.save(specGroup);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }
    @PutMapping("/group")
    public ResponseEntity<Void> updateGroup(@RequestBody SpecGroupDTO specGroupDTO){
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        specGroupService.updateById(specGroup);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
    @PostMapping("/param")
    public ResponseEntity<Void> inputSpecparam(@RequestBody SpecParamDTO specParamDTO){
        //转为entity对象
        SpecParam specParam = specParamDTO.toEntity(SpecParam.class);
        specParamService.save(specParam);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    @PutMapping("/param")
    public ResponseEntity<Void> updateSpecparam(@RequestBody SpecParamDTO specParamDTO){
        SpecParam specParam = specParamDTO.toEntity(SpecParam.class);
        specParamService.updateById(specParam);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
    @GetMapping("/list")
    public ResponseEntity<List<SpecGroupDTO>> queryBycategoryId(@RequestParam("id")Integer id){
        //查询规格参数和规格组
        //SpecGroup中封装了规格参数
        //返回规格参数组
        List<SpecGroupDTO> specGroupDTOS = specGroupService.querySpecGroup(id);
        return ResponseEntity.ok(specGroupDTOS);
    }




}
